package xin.yangshuai.generator01.service.impl;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.yaml.snakeyaml.Yaml;
import xin.yangshuai.generator01.entity.ModuleInfo;
import xin.yangshuai.generator01.service.ModuleService;

import java.io.File;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Service
public class ModuleServiceImpl implements ModuleService {

    @Value("${absolute-path-root}")
    private String absolutePathRoot;

    @Value("${module-info-file}")
    private String moduleInfoFile;


    /**
     * 获取module列表
     *
     * @return
     */
    @Override
    public List<ModuleInfo> list() {

        File file = new File(absolutePathRoot);

        List<ModuleInfo> list = new ArrayList<>();

        findModule(file, list, "");

        return list;
    }

    private void findModule(File file, List<ModuleInfo> moduleInfoList, String parentModuleName) {

        if (!file.exists()) {
            return;
        }

        String fileName = file.getName();
        System.out.println("fileName:" + fileName);

        if (StringUtils.equalsAnyIgnoreCase(fileName, ".idea", ".git", "doc", "sql")) {
            return;
        }

        if (StringUtils.equalsAnyIgnoreCase(fileName, "important-project")) {
            fileName = "";
        }

        String moduleName = parentModuleName + fileName;


        if (file.isDirectory()) {

            // 如果当前文件是目录，获取当前目录下是否有 /src ，如果有，则认为是web工程目录，不需要再遍历该目录下的其它子文件夹
            // 如果当前文件夹有 /src，获取当前目录下是否有 /src/main/resources/application.yml
            // 如果当前文件夹没有 /src，则遍历所有子目录

            String srcAbsolutePath = file.getAbsolutePath() + "/src";
            File srcFile = new File(srcAbsolutePath);

            System.out.println("src:" + srcAbsolutePath + " exists:" + srcFile.exists());

            if (srcFile.isDirectory()) {
                String fileAbsolutePath = file.getAbsolutePath();
                String ymlAbsolutePath = fileAbsolutePath + "/src/main/resources/application.yml";

                File ymlFile = new File(ymlAbsolutePath);

                System.out.println("application.yml:" + ymlAbsolutePath + " exists:" + ymlFile.exists());

                if (ymlFile.exists()) {
                    // 如果有application.yml，则获取端口号、模块名称、context-path

                    ModuleInfo moduleInfo = new ModuleInfo();
                    moduleInfoList.add(moduleInfo);

                    Yaml yml = new Yaml();
                    try (InputStream reader = Files.newInputStream(Paths.get(ymlAbsolutePath));) {

                        Integer port = null;
                        String contextPath = null;

                        // 只获取一个yml文件中的第一个文档
                        Iterable<Object> ymlIterable = yml.loadAll(reader);
                        Iterator<Object> ymlIterator = ymlIterable.iterator();
                        Map ymlMap = (Map) ymlIterator.next();

                        if (ymlMap != null) {
                            Map serverMap = (Map) ymlMap.get("server");
                            if (serverMap != null) {
                                port = (Integer) serverMap.get("port");

                                Map servletMap = (Map) serverMap.get("servlet");
                                if (servletMap != null) {
                                    contextPath = (String) servletMap.get("context-path");
                                }
                            }
                        }

                        moduleInfo.setPort(port);
                        moduleInfo.setContextPath(contextPath);
                        moduleInfo.setModuleName(moduleName);
                        moduleInfo.setUrl("http://localhost" + (port != null ? ":" + port : "") + (contextPath != null ? contextPath : ""));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            } else {
                // 当前文件夹没有 /src，遍历所有子目录
                File[] files = file.listFiles();
                if (files != null) {
                    for (File f : files) {
                        if (StringUtils.isNotBlank(moduleName) && !moduleName.endsWith("-")) {
                            moduleName = moduleName + "-";
                        }
                        findModule(f, moduleInfoList, moduleName);
                    }
                }
            }
        }
    }

    /**
     * 在所有module中，获取当前的最大端口号
     *
     * @return
     */
    @Override
    public int maxPort() {
        List<ModuleInfo> moduleInfoList = list();

        int maxPort = 0;

        for (ModuleInfo moduleInfo : moduleInfoList) {
            Integer port = moduleInfo.getPort();
            if (port != null && port > maxPort) {
                maxPort = port;
            }
        }
        return maxPort;
    }

    /**
     * 生成md文件
     */
    @Override
    public void writeMd() {
        try {
            StringBuilder mdContent = new StringBuilder("|module-name|context-path|port|url|\n");
            mdContent.append("|:---|:---|:---|:---|\n");

            List<ModuleInfo> moduleInfoList = list();

            for (ModuleInfo module : moduleInfoList) {
                String moduleInfoText = String.format("|%s|%s|%d|%s|\n", module.getModuleName(), module.getContextPath(), module.getPort(), module.getUrl());
                mdContent.append(moduleInfoText);
            }

            Files.write(Paths.get(moduleInfoFile), mdContent.toString().getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
